﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ToDoIt2.Model.Persistent.UI;
using ToDoIt2.Aspects;
using MonitoredUndo;
using System.Diagnostics;
using ToDoIt2.ViewModel;

namespace ToDoIt2.UI {
	/// <summary>
	/// Interaction logic for TabItem.xaml
	/// </summary>
	[NotifyPropertyChanged]
	public partial class TabItem : System.Windows.Controls.TabItem {
		protected App App { get { return (App.Current as App); } }

		public TabPrefsVM TabPrefs { get { return this.DataContext as TabPrefsVM; } }

		private UndoBatch EditingUndoBatch = null;

		public TabItem()
			: base() {
			InitializeComponent();
		}

		private void OnHeaderMouseDown(object sender, MouseButtonEventArgs e) {
			if (e.ClickCount == 2)
				this.StartTitleEdit();
		}

		private void OnEditHeaderLostFocus(object sender, RoutedEventArgs e) {
			if (this.TabPrefs.EditingHeader)
				this.TabPrefs.EditingHeader = false;
		}

		private void OnEditHeaderInitialized(object sender, EventArgs e) {
			(sender as TextBox).Focus();
			(sender as TextBox).SelectAll();
		}

		private void OnPreviewKeyDown(object sender, KeyEventArgs e) {
			switch (e.Key) {
				case Key.Return:
					if (this.TabPrefs.EditingHeader)
						this.CaptureTitleChange();
					else
						this.StartTitleEdit();
					e.Handled = true;
					break;
				case Key.Escape:
					if (this.TabPrefs.EditingHeader) {
						this.CancelTitleChange();
						e.Handled = true;
					}
					break;
			}
		}


		private void StartTitleEdit() {
			this.TabPrefs.EditingHeader = true;
		}
		private void CaptureTitleChange() {
			// Setting focus causes binding to update target upon focus loss from text box (and thus editing to end via LostFocus event)
			this.Focus();
		}
		private void CancelTitleChange() {
			this.TabPrefs.EditingHeader = false;
		}
	}
}
